import store from "../store/index.js"

// #ifdef APP-PLUS
// const BASE_URL = "http://192.168.2.124:9999"
// const BASE_URL = "http://192.168.2.201:9999"
// const BASE_URL = "http://8.140.111.119:9003/api/"	
const BASE_URL = "http://47.94.213.158:9006/api/"
// #endif
// #ifdef H5
const BASE_URL = "/api"
// #endif
const request = {};
request.get = (url, data, ...args) => {
	return requestFunction(url, 'GET', data, args)
}
request.post = (url, data, ...args) => {
	return requestFunction(url, 'POST', data, args)
}
request.delete = (url, data, ...args) => {
	return requestFunction(url, 'DELETE', data, args)
}
request.put = (url, data, ...args) => {
	return requestFunction(url, 'PUT', data, args)
}
const requestFunction = (url, method, data, args) => {
	const {
		vuex_user
	} = store.state
	return new Promise((resolve, reject) => {
		// console.log(data);
		uni.request({
			url: BASE_URL + url,
			method,
			data,
			...args,
			header: {
				"token": vuex_user && vuex_user.token || "",
				"platform":"app"
			},
			success(res) {
				if (res.data.code === 1500) {
					uni.removeStorageSync('user')
					uni.showToast({
						title: '当前用户已过期，请重新登录！',
						icon: "none"
					})
					uni.reLaunch({
						url: "/pages/login/login",
					})
					return;
				}
				if (res.data.code === 0) {
					resolve(res.data.data)
				} else {
					uni.showToast({
						icon: "none",
						title: res.data.msg || '获取数据异常！',
						duration: 1500
					})
					reject()
				}
			},
			fail(err) {
				if (err.errMsg.indexOf("timeout") !== -1) {
					uni.showToast({
						title: '网络异常！'
					})
				}
				console.log('获取数据异常！', err);
				reject(err)
			},
			complete() {
				// console.log('complete');
				resolve()
			}
		})
	})
}

export default request
